chrome.runtime.onInstalled.addListener(function () {
  alert('installed')
  chrome.storage.sync.set({ color: '#3aa757' }, function () {
    console.log('Value is set to #3aa757')
  })
})

// 获取当前选项卡ID
async function getCurrentTabIdAsync() {
  let { id } = await getCurrentTabAsync()
  return id
  // return new Promise((resolve, reject) => {
  //   chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
  //     tabId = tabs.length ? tabs[0].id : null
  //     resolve(tabId)
  //   })
  // })
}
/**
 * @desc 获取当前标签窗口
 */
function getCurrentTabAsync() {
  return new Promise((resolve, reject) => {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      tab = tabs.length ? tabs[0] : null
      resolve(tab)
    })
  })
}

/**
 * @description: 封装获取url参数类
 * @param {type}
 * @return {Object}
 */
function GetUrlParam(url) {
  return (function() {
    this.parameter = url.split('?')[1] // 获取url中"?"符后的字串
    this.parameterJson = {} // 保存参数数据的对象
    this.parameterArr = this.parameter && this.parameter.length ? this.parameter.split('&') : [] // 取得每一个参数项,

    this.item = null
    this.len = this.parameterArr.length
    var _this = this
    for (var i = 0; i < this.len; i++) {
      //这里写代码片
      _this.item = _this.parameterArr[i].split('=')
      _this.name = decodeURIComponent(_this.item[0]) // URI 进行解码。
      _this.value = decodeURIComponent(_this.item[1]) // URI 进行解码。
      if (_this.name) {
        _this.parameterJson[_this.name] = decodeURIComponent(_this.value)
      }
    }
    return this.parameterJson
  })()
}

chrome.storage.onChanged.addListener(function (changes, namespace) {
  for (var key in changes) {
    var storageChange = changes[key]
    console.log(
      'Storage key "%s" in namespace "%s" changed. ' +
        'Old value was "%s", new value is "%s".',
      key,
      namespace,
      storageChange.oldValue,
      storageChange.newValue
    )
  }
})

let webMessage = document.getElementById('webMessage')

webMessage.addEventListener('click', function () {
  chrome.storage.sync.get('color', function (data) {
    webMessage.setAttribute('value', data.color)
    webMessage.style.backgroundColor = data.color
  })
  chrome.runtime.sendMessage('Hello', function (response) {
    console.log('response', response)
  })

  getCurrentTabIdAsync().then((tabId) => {
    // 动态执行JS文件
    chrome.tabs.executeScript(tabId, { file: 'js/action_script.js' })
    chrome.tabs.executeScript(tabId, { code: 'testFetch()' })

    var port = chrome.tabs.connect(tabId, { name: 'test-connect' })
    port.postMessage({ question: '你是谁啊？' })
    port.postMessage({ type: 'PLAY_VIDEO' })

    port.onMessage.addListener(function (msg) {
      console.log('收到消息：' + msg.answer)
      if (msg.answer && msg.answer.startsWith('我是')) {
        port.postMessage({ question: '哦，原来是你啊！' })
      }
    })
    chrome.tabs.getCurrent(function(tab) {
      console.log("tab", tab)
    })
  })
})

let buttonNote = document.querySelector('#postNote')
let buttonCancle = document.querySelector('#postCancle')
let clickEvent = new Event('click')
buttonNote.addEventListener('click', function () {
  console.log('开始刷课', buttonNote.node)
  if(!buttonNote.dataset.isBeginning) {
    getCurrentTabAsync().then((tab) => {
      console.log('tab', tab)
      let { kpointNo, kName } = new GetUrlParam(tab.url)
      chrome.tabs.executeScript(tab.id, { code: `actionNote(${kpointNo}, '${kName}')` })
      buttonNote.innerHTML = '取消刷课'
      buttonNote.dataset.isBeginning = true
    })
  } else {
    console.log('取消刷课')
    getCurrentTabIdAsync().then((tabId) => {
      chrome.tabs.executeScript(tabId, { code: 'canclePostAction()' })
      buttonNote.innerHTML = '开始刷课'
      buttonNote.dataset.isBeginning = false
    })
  }
})

let buttonInserter = document.querySelector('#btnInsertHistory')
/**
 * @desc 完成插入学习历史
 */
function cbDoneInsertHistory(resp) {
  buttonInserter.innerHTML = '完成本节刷课'
}
buttonInserter.addEventListener('click', function() {
  getCurrentTabAsync().then(tab => {
    let query = new GetUrlParam(tab.url)
    let fn = chrome.tabs.executeScript(tab.id, {code: `modifyStudyHistory(${JSON.stringify(query)})`})
    console.log("fn", fn)
  })
})


buttonCancle.addEventListener('click', function () {
  console.log('取消刷课')
  getCurrentTabIdAsync().then((tabId) => {
    chrome.tabs.executeScript(tabId, { code: 'canclePostAction()' })
  })
})
